﻿using Ipmce.RemoteVoting.Backend.DataAccess;
using Ipmce.RemoteVoting.Backend.DataAccess.Exceptions;
using Ipmce.RemoteVoting.Backend.SmsGateway.Exceptions;
using Ipmce.RemoteVoting.Backend.SmsGateway.Utils;

namespace Ipmce.RemoteVoting.Backend.SmsGateway.Processing
{
	class RequestProcessor : IRequestProcessor
	{
		private readonly IVoterSmsInfoParser _parser;
		private readonly IVoterRepository _voterRepository;
		private readonly ISmsConfirmationGenerator _confirmationGenerator;

		public RequestProcessor(IVoterSmsInfoParser parser, 
			IVoterRepository voterRepository,
			ISmsConfirmationGenerator confirmationGenerator)
		{
			_parser = parser;
			_voterRepository = voterRepository;
			_confirmationGenerator = confirmationGenerator;
		}

		public string ProcessSmsCode(string smsRequest)
		{
			var voterInfo = _parser.Parse(smsRequest);
			Voter voter;
			try
			{
				voter = _voterRepository.GetByPassportNumber(voterInfo.PassportNumber);
			}
			catch (EntityNotFoundException)
			{
				throw new VoterNotFoundException();
			}
			if (voter.BirthDate != voterInfo.Birthdate.Date)
			{
				throw new VoterNotFoundException();
			}
			var code = _confirmationGenerator.Generate();
			voter.SmsCode = code;
			_voterRepository.CommitChanges();
			return code;
		}
	}
}